package com.lngsyz.file.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.ResourceBundle;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

public class StringUtil {
	
	// 编码方式
    private static final String ENCODE_UTF = "UTF-8";
    
    /**
	 * 获取资源文件
	 * 
	 * @param propertiesFile
	 * @param itemIndex
	 * @return
	 */
	public static String getConfiguration(String propertiesFile, String itemIndex) {
		try {
			Configuration configs = new PropertiesConfiguration(propertiesFile);
			return configs.getString(itemIndex);
		} catch (Exception e) {
			return "";
		}
	}
    
    /**
     * number
     * @param str
     * @return
     */
	public static boolean isNumeric(String str) {
		if(StringUtils.isNotBlank(str)) {
			for (int i = str.length(); --i >= 0;) {
				if (!Character.isDigit(str.charAt(i))) {
					return false;
				}
			}
			return true;
		} else {
			return false;
		}
	}
    
	/**
     * 计算中英文字符串的字节长度 <br/>
     * 一个中文占3个字节
     *
     * @param str
     * @return int 字符串的字节长度
     */
    public static int getLength(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        try {
            return str.getBytes(ENCODE_UTF).length;
        } catch (UnsupportedEncodingException e) {
        	e.printStackTrace();
        }
        return 0;
    }

	public static String createUuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	public static String getConfig(String propertiesFile, String itemIndex) {
		String configStr = "";
		try {
			configStr = ResourceBundle.getBundle(propertiesFile).getString(itemIndex);
		} catch (Exception e) {
		}
		return configStr;
	}
	
	public static boolean isCorrectPhone(String phone) {
		boolean flag = false;
		if(isMobile(phone) || isPhone(phone)) {
			flag = true;
		}
		return flag;
	}
	
	@SuppressWarnings("rawtypes")
	public static String listToString(List list) {
		String s = org.apache.commons.lang.StringUtils.join(list.toArray(), ",");
		return s;
	}

	/**
     * 手机号验证
     * 
     * @param  str
     * @return 验证通过返回true
     */
    private static boolean isMobile(String str) { 
        Pattern p = null;
        Matcher m = null;
        boolean b = false; 
        p = Pattern.compile("^[1][3,4,5,6,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches(); 
        return b;
    }
    /**
     * 电话号码验证
     * 
     * @param  str
     * @return 验证通过返回true
     */
    private static boolean isPhone(String str) { 
        Pattern p1 = null,p2 = null;
        Matcher m = null;
        boolean b = false;  
        p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$");  // 验证带区号的
        p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$");         // 验证没有区号的
        if(str.length() >9)
        {   m = p1.matcher(str);
           b = m.matches();  
        }else{
            m = p2.matcher(str);
           b = m.matches(); 
        }  
        return b;
    }
    
    public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
    
    public static byte[] getImage(String filePath) throws Exception {
		File f = new File(filePath);
        if (!f.exists()) {
            throw new FileNotFoundException(filePath);
        }
 
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(f));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
            }
            bos.close();
        }
//        FileInputStream inputStream = new FileInputStream(file);
//        byte[] bytes = new byte[inputStream.available()];
//        inputStream.read(bytes, 0, inputStream.available());
//        return bytes;
    }
    
    public static String findDistrict4ByInstCode(String instCode) {
    	String rtn = "";
    	if(StringUtils.length(instCode) == 18) {
    		rtn = StringUtils.substring(instCode, 2, 6);
    	}
    	return rtn;
    }
    
    public static String findDistrict6ByInstCode(String instCode) {
    	String rtn = "";
    	if(StringUtils.length(instCode) == 18) {
    		rtn = StringUtils.substring(instCode, 2, 8);
    	}
    	return rtn;
    }
    
    /**
     * 将MultipartFile转换为File
     * @param multiFile
     * @return
     */
    public static File multipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static void writeBytesToResponse(HttpServletResponse response, byte[] bytes, String fileName) throws IOException {
    	writeBytesToResponse(response, null, bytes, fileName);
    }
    
    public static void writeBytesToResponse(HttpServletResponse response, ContentType contentType, byte[] bytes, String fileName) throws IOException {
    	if(bytes != null && bytes.length > 0) {
    		// 获取输出流
    		OutputStream outputStream = response.getOutputStream();
    		try {
    			// 设置响应的内容类型和编码
    			if(contentType != null) {
    				response.setContentType(contentType.toString());
    			} else {
    				response.setContentType("application/octet-stream");
    			}
    			response.setCharacterEncoding("UTF-8");
    			response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
    			// 写入字节数组到输出流
    			outputStream.write(bytes);
    			System.out.print("0");
    		} catch(Exception e) {
    			throw e;
    		} finally {
    			// 清空缓冲区，结束响应
    			outputStream.flush();
    			outputStream.close();
    		}
    	}
    }

    public static void returnJson(HttpServletResponse response, String rtnStr) throws Exception {
    	if(response != null) {
    		PrintWriter writer = null;
    		response.setCharacterEncoding("UTF-8");
    		response.setContentType("text/html; charset=utf-8");
    		try {
    			writer = response.getWriter();
    			writer.print(rtnStr);
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			if (writer != null)
    				writer.close();
    		}
    	}
	}
    
    public static void returnJsonErr500(HttpServletResponse response, String msg) throws Exception {
    	PrintWriter writer = null;
    	response.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	try {
    		JSONObject errObj = new JSONObject();
    		errObj.put("code", 500);
    		errObj.put("msg", msg);
    		writer = response.getWriter();
    		writer.print(errObj.toJSONString());
    	} catch (IOException e) {
    		e.printStackTrace();
    	} finally {
    		if (writer != null)
    			writer.close();
    	}
    }
    
    public static void returnJsonErr0(HttpServletResponse response, String msg) {
    	PrintWriter writer = null;
    	response.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	try {
    		JSONObject errObj = new JSONObject();
    		errObj.put("code", 0);
    		errObj.put("msg", msg);
    		writer = response.getWriter();
    		writer.print(errObj.toJSONString());
    	} catch (IOException e) {
    		e.printStackTrace();
    	} finally {
    		if (writer != null)
    			writer.close();
    	}
    }
}
